﻿using GraphQL.Client.Http;
using GraphQL.Client.Serializer.Newtonsoft;
using HotChocolate.Language;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Volo.Abp.UI.Navigation.DefaultMenuNames.Application;

namespace Himp.Platform
{
    /// <summary>
    /// 内部API
    /// </summary>
    [Route("api/internalApi/v1")]
    public class ApiQueryController : ApiBaseController
    {
        private IOpenApiService _openApiService;

        public ApiQueryController(IOpenApiService openApiService)
        {
            _openApiService = openApiService;
        }

        [HttpPost]
        public async Task<InternalApiOutput> Post([FromBody] InternalApiInput input)
        {
            InternalApiOutput internalApiOutput = new InternalApiOutput();
            internalApiOutput.RefMsgId = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            internalApiOutput.RecvTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            internalApiOutput.ResTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            var graphQlClient = new GraphQLHttpClient("https://localhost:44322/graphql/", new NewtonsoftJsonSerializer());
            var query = new GraphQLHttpRequest(input.Input);

            try
            {
                var response = await graphQlClient.SendQueryAsync<object>(query);

                if (response.Errors?.Any() == true)
                {
                    StringBuilder errorSB = new StringBuilder();
                    internalApiOutput.InfStasno = -1;
                    foreach (var error in response.Errors)
                    {
                        errorSB.AppendLine(error.Message);
                    }
                    internalApiOutput.ErrMsg = errorSB.ToString();
                }
                else
                {
                    var dataJson = Newtonsoft.Json.JsonConvert.SerializeObject(response.Data);
                    internalApiOutput.Output = dataJson;
                }
            }
            catch (Exception e)
            {
                internalApiOutput.InfStasno = -1;
                internalApiOutput.ErrMsg = e.Message;
            }

            return internalApiOutput;
        }
    }
}
